/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.qb9.flashlib.logs
{
	import com.qb9.flashlib.interfaces.IDisposable;
	
	import flash.events.AsyncErrorEvent;
	import flash.events.Event;
	import flash.events.SecurityErrorEvent;
	import flash.events.StatusEvent;
	import flash.net.LocalConnection;
	import flash.utils.getTimer;
	
	/**
	 * Sends the logs to an external flash player using a LocalConnection
	 * 
	 * To see the logs, you need the compiled swf from the project called flogger
	 * found on QB9's svn repository (by that name).
	 */
	
	public class FloggerAppender implements IAppender, IDisposable
	{
		private static const ERROR_STATUS:String = 'error';
		private static const ERROR_TIMEOUT:uint = 5e3;
		
		private var connectionName:String;
		private var connection:LocalConnection;
		
		private var errorStamp:int = -ERROR_TIMEOUT;
		
		public function FloggerAppender(connectionName:String='_flash_logger')
		{
			this.connectionName = connectionName;
			
			init();
		}
		
		private function init():void
		{
			connection = new LocalConnection();
			connection.allowDomain('*');
			connection.allowInsecureDomain('*');
			connection.addEventListener(AsyncErrorEvent.ASYNC_ERROR, ignore);
			connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, ignore);
			connection.addEventListener(StatusEvent.STATUS, checkStatus);
		}
		
		private function ignore(e:Event):void
		{
		}
		
		private function checkStatus(e:StatusEvent):void
		{
			if (e.level === ERROR_STATUS)
				failed();
		}
		
		private function failed():void
		{
			errorStamp = getTimer();
		}
		
		/** @inheritDoc */
		public function append(msg:Array,level:int):void
		{
			if (getTimer() - errorStamp < ERROR_TIMEOUT)
				return;
			
			try{
				connection.send(connectionName, getMethodName(level), msg.join(' '));
			}catch(err:Error){
				failed();
			}
		}
		
		private function getMethodName(num:int):String
		{
			switch(num)
			{
				default:
				case Logger.LOG_LEVEL_NONE     : return 'log';
				case Logger.LOG_LEVEL_INFO     : return 'info';
				case Logger.LOG_LEVEL_DEBUG    : return 'debug';
				case Logger.LOG_LEVEL_WARNING  : return 'warning';
				case Logger.LOG_LEVEL_ERROR	   : return 'error';				
			}
		}
		
		public function dispose():void
		{
			connection.removeEventListener(AsyncErrorEvent.ASYNC_ERROR, ignore);
			connection.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, ignore);
			connection.removeEventListener(StatusEvent.STATUS, checkStatus);
			connection = null;
		}
	}
}
